package org.shuaibi.hi_blog.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.json.JSONObject;

import android.content.Context;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

public class CallWebservice  {

	private final String HTTPHOST="http://blog.haojima.net/api/home/";
	public static RequestQueue requestQueue;
	private Context mContnxt;
	private int mMark;
	private ServiceCallBack mServiceCallBack;

	public CallWebservice(Context context,String function,HashMap<String, String> params,int mark)
	{
		this.mContnxt=context;
		this.mMark=mark;
		this.mServiceCallBack=(ServiceCallBack) context;
		createUrl(function,params);
	}

	public void createUrl(String function,HashMap<String, String> params)
	{
		//拼主机名和方法名
		String url=this.HTTPHOST+function;
		//拼参数
		if(params!=null){
			url+="?";
			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> obj = (Entry<String, String>) iterator.next();
				url+=obj.getKey().toString()+"="+obj.getValue().toString()+"&";
			}
			url=url.substring(0, url.length()-1);
		}
		//请求服务器
		getJsonResult(url);

	}

	public void getJsonResult(String url)
	{
		if(CallWebservice.requestQueue==null)
		{
			requestQueue=Volley.newRequestQueue(mContnxt);
		}
		JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(url, null, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				mServiceCallBack.serviceResult(response, mMark);
			}
		}, new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
		     Toast.makeText(mContnxt, error.getMessage(), Toast.LENGTH_SHORT).show();
			}
		});
		requestQueue.add(jsonObjectRequest);
	}
}
